local _M = {}
require "config"

local function check_login()
    local session = require "resty.session".open()
    if session.present then
        ngx.log(ngx.ERR,session.data.user_name)
        if session.data.user_name == "mind" then
                return 
        end
    end
    ngx.redirect('login')
end

function _M.login(in_html_template_dir)
    local http_method = ngx.req.get_method()
    local template = require "resty.template"
    local template_name = "login.html"
    local p = {}
    if http_method == 'GET' then
        ngx.log(ngx.ERR, http_method)
        local session = require "resty.session".open()
        -- Read some data
        if session.present then
            if session.data.user_name == "mind" then
                return ngx.redirect("index")
            end
        end
    elseif http_method == 'POST' then
        ngx.req.read_body()
        local args, err = ngx.req.get_post_args(5)
        if not args then
             p.info=err
        else
            ngx.log(ngx.ERR, args['user_name'], args['password'])
            if args['user_name'] ~= 'mind'  then
                p.info='用户名或密码错误'
                p.in_html_template_dir = in_html_template_dir
                return template.render(template_name, p)
            end
            if args['password'] ~= '123456'  then
                p.info='用户名或密码错误'
                p.in_html_template_dir = in_html_template_dir
                return template.render(template_name, p)
            end    
            local session = require "resty.session".open()
            -- Read some data
            if session.present then
                if session.data.user_name == "mind" then
                    return ngx.redirect("index")
                end
            end
            -- Now let's really start the session
            -- (session.started will be always false in this example):
            if not session.started then 
                session:start()
            end
            session.data.user_name = args['user_name']
            session:save()
            return ngx.redirect("index")                
        end
    end
    ngx.log(ngx.ERR, in_html_template_dir)
    p.in_html_template_dir = in_html_template_dir
    return template.render(template_name, {p=p})
end

function _M.index()
    check_login()
    local template = require "resty.template"
    return template.render('index.html', { url=route_table   })

end


function _M.logout()
    local session = require "resty.session".start()
    session:destory()
    return ngx.ngx.redirect("login")
end

return _M

